package org.example.service.impl;

import cn.hutool.core.bean.BeanUtil;
import org.example.dao.ISysMenuDao;
import org.example.dao.ISysRoleDao;
import org.example.domain.entity.SysMenu;
import org.example.domain.entity.SysRole;
import org.example.domain.vo.MenuVo;
import org.example.service.ISysMenuService;
import org.example.utils.SecurityUtil;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysMenuServiceImpl implements ISysMenuService {
    private final ISysRoleDao sysRoleDao;
    private final ISysMenuDao sysMenuDao;

    public SysMenuServiceImpl(ISysRoleDao sysRoleDao, ISysMenuDao sysMenuDao) {
        this.sysRoleDao = sysRoleDao;
        this.sysMenuDao = sysMenuDao;
    }

    @Override
    public List<MenuVo> getListMenuVos(){
        List<SysRole> sysRoles = SecurityUtil.getLoginUser().getUser().getRoles();
        List<Long> roleIds = sysRoles.stream().map(SysRole::getId).collect(Collectors.toList());
        List<SysMenu> sysMenus = sysMenuDao.selectMenuByRoleId(roleIds);
        return getParentMenu(sysMenus);
    }

    public List<MenuVo> getParentMenu(List<SysMenu> menus){
        List<MenuVo> parentMenuVos = new ArrayList<>();
        List<SysMenu> parentMenu = menus.stream().filter(item -> item.getParentId() == 0).collect(Collectors.toList());
        for (SysMenu menu : parentMenu) {
            MenuVo menuVo = new MenuVo();
            BeanUtil.copyProperties(menu,menuVo);
            parentMenuVos.add(menuVo);
        }

        for (MenuVo parentMenuVo : parentMenuVos) {

            List<MenuVo> menuVos = bindTree(parentMenuVo.getId(), menus);
            parentMenuVo.setMenuVos(menuVos);
        }
        return parentMenuVos;
    }

    public List<MenuVo> bindTree(Long parentId,List<SysMenu> allMenus){
        List<MenuVo> childMenuVos = new ArrayList<>();

        for (SysMenu childMenu : allMenus) {
            if(childMenu.getParentId() == parentId){
                MenuVo menuVo = new MenuVo();
                BeanUtil.copyProperties(childMenu,menuVo);
                childMenuVos.add(menuVo);
            }

        }
        for (MenuVo childMenuVo : childMenuVos) {
            childMenuVo.setMenuVos(bindTree(childMenuVo.getId(),allMenus));
        }
        return childMenuVos;
    }
}
